import { message, Divider } from 'antd';
import moment from 'moment';
import React, { useRef } from 'react';
import { pickBy } from 'lodash';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ActionType } from '@ant-design/pro-table';

import { TableListItem } from './data';
import { arrayToObject, isNilAndEmpty } from '@/utils/utils';
import { queryRule, removeRule } from './service';
import AddModal from './components/AddModal';
import { COUPON_TYPE, PLATFORM_TYPE } from '@/common/constants';



/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: TableListItem[], action: any) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeRule({
      key: selectedRows.map((row) => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    action.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const addRef = useRef();

  const columns: any[] = [
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: '优惠券名称',
      dataIndex: 'name',
    },
    {
      title: '优惠卷类型',
      dataIndex: 'type',
      hideInSearch: true,
      render: (v: number) => arrayToObject(COUPON_TYPE, 'value')?.[v]
    },
    {
      title: '优惠券开始时间',
      dataIndex: 'coupon_start_time',
      hideInSearch: true,
      render: (v: number | string) => v !== '-' ? moment((v as number)).format('YYYY-MM-DD') : '-',
    },
    {
      title: '优惠券结束时间',
      dataIndex: 'coupon_end_time',
      hideInSearch: true,
      render: (v: number | string) => v !== '-' ? moment((v as number)).format('YYYY-MM-DD') : '-',
    },
    {
      title: '使用平台',
      dataIndex: 'platform',
      hideInSearch: true,
      render: (v: number) => arrayToObject(PLATFORM_TYPE, 'value')?.[v]
    },
    {
      title: '面额（元）',
      dataIndex: 'amount',
      hideInSearch: true,
    },
    {
      title: '使用门槛（元）',
      dataIndex: 'min_point',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'create_at',
      hideInForm: true,
      hideInSearch: true,
      render: (v: number) => moment(v * 1000).format('YYYY-MM-DD'),
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record, index, action) => (
        <>
          <a
            onClick={() => {
              addRef.current?.edit(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a
            onClick={async () => {
              await handleRemove([record], action);
            }}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<TableListItem>
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        params={{}}
        toolBarRender={() => [
          <AddModal ref={addRef} callback={() => actionRef.current?.reload()}></AddModal>,
        ]}
        request={async (params) => {
          const ans = {
            ...params,
            page: params?.current,
          };
          delete ans.current;
          const filterAns = pickBy(ans, isNilAndEmpty);
          const { data } = await queryRule(filterAns);
          data.data = data.list;
          return data;
        }}
        columns={columns}
        rowSelection={{}}
      />
    </PageHeaderWrapper>
  );
};

export default TableList;
